import { PickerSelectorProps, Picker } from '@tarojs/components';
import {
  FC,
  ReactNode,
  useCallback,
  useEffect,
  useMemo,
  useRef,
  useState,
} from 'react';

import './index.scss';

interface OurSelectProps
  extends Omit<PickerSelectorProps, 'value' | 'onChange' | 'range'> {
  label: string | ReactNode;
  value?: number;
  options: { label: string; value: number }[];
  onChange?: (e: number, label?: string) => void;
}

const OurSelect: FC<OurSelectProps> = (props) => {
  const [isFocus, setIsFocus] = useState(false);
  const [value, setValue] = useState<number | null>(null);
  const iptRef = useRef<HTMLSelectElement | null>(null);

  const init = useCallback(() => {
    !!props.value && setValue(props.value);
    setIsFocus(!!props.value);
  }, [props.value]);

  useEffect(() => {
    init();
  }, [init]);

  const getRangesFromProps = useMemo(() => {
    return props.options.map((item) => item.label);
  }, [props.options]);

  const getIndexByValue = useMemo(() => {
    return props.options.findIndex((item) => item.value === value);
  }, [props.options, value]);

  const getLabelByValue = useMemo(() => {
    return props.options.find((item) => item.value === value)?.label;
  }, [props.options, value]);

  const changeValue = (e) => {
    const inputValue = e.detail.value;
    const realValue = props.options[inputValue].value;
    setValue(realValue);
    !!props.onChange &&
      props.onChange(realValue, props.options[inputValue].label);
  };

  const focusSelect = () => {
    setIsFocus(true);
    iptRef.current && iptRef.current.focus();
  };

  const cancelSelect = () => {
    setIsFocus(!!value);
    iptRef.current && iptRef.current.blur();
  };

  return (
    <div className={props.className || ''}>
      <Picker
        {...props}
        mode="selector"
        value={getIndexByValue}
        range={getRangesFromProps}
        ref={iptRef}
        onChange={changeValue}
        onCancel={cancelSelect}
      >
        <div
          className={
            'thisSelectGroup' + (isFocus ? ' focusThisSelectGroup' : '')
          }
          onClick={focusSelect}
        >
          <div className="thisSelect">{getLabelByValue}</div>
          <div className="thisSelectOthers">
            <div className="bar">
              <p className="barLineError barLine" />
              <p className="barLineLeft barLine" />
              <p className="barLineRight barLine" />
            </div>
            <label className="thisLabel">{props.label}</label>
          </div>
        </div>
      </Picker>
    </div>
  );
};

export default OurSelect;
